#include <unistd.h>
#include <time.h>
#include "cnats.h"
#include "clog.h"
#include "threads.h"

sem_t window;

class testWorker:public worker{
private:
    int threadNum;
public:
    testWorker(int num){
        threadNum = num;
    }
    void run(void){
        clog::d("worker:");
        clog::d(threadNum);
        clog::dl("running");
        usleep(rand()%10000);
        clog::d("END: ");
        clog::dl(threadNum);
    }
    void stop(){
        clog::dl("STOP Called");
    }
};

void testForThreads(){
    clog::dl("ThreadTestStart");
    srand((int)time(0));
    threads ths = threads(20);

    for(int i = 0; i < 5; i++){
        ths.addJob(new testWorker(i));
        usleep(rand()%10000);
    }
    ths.stop();
    clog::dl("ThreadTestEnd");
}

class testHandler: public MsgHandler {
public:
    void execute(recvedMsgs *msg){
        clog::dl("Recved PONG");
        sem_post(&window);
    }
};

const int len = 1024 * 4;
char data[len];

int main(int argc, char const *argv[]){
    clog::setLevel(2);
    clog::dl("Start");
    sem_init(&window,0,8000);
    for (int i = 0; i < len; ++i){
        data[i] = 'b';
    }
    // testForThreads();
    cnats* conn = cnats::Connect("nats://localhost:4222,nats://localhost:4223,nats://localhost:4224");
    conn->Subscribe("PONG",new testHandler());
    clog::dl("Enter Sleep");
    while(1){
        sem_wait(&window);
        conn->Publish("PING",data,len);
    }
    return 0;
}
